package com.controller;

import cn.hutool.core.collection.CollUtil;
import com.annotation.IgnoreAuth;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.entity.YiShengEntity;
import com.entity.view.YonghuView;
import com.service.TokenService;
import com.service.UsersService;
import com.service.YiShengService;
import com.utils.MPUtil;
import com.utils.PageUtils;
import com.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户
 * 后端接口
 *
 * @author
 * @email
 * @date 2025-03-04
 */
@RestController
@RequestMapping("/yisheng")
public class YiShengController {
    @Autowired
    private YiShengService yonghuService;


    @Autowired
    private TokenService tokenService;


    @Autowired
    private UsersService usersService;

    /**
     * 登录
     */
    @IgnoreAuth
    @RequestMapping(value = "/login")
    public R login(String username, String password, String captcha, HttpServletRequest request) {
        YiShengEntity user = yonghuService.selectOne(new EntityWrapper<YiShengEntity>().eq("yonghuzhanghao", username));
        if (user == null || !user.getMima().equals(password)) {
            return R.error("账号或密码不正确");
        }
        String token = tokenService.generateToken(user.getId(), username, "yisheng", "客户");
        ArrayList<String> strings = CollUtil.newArrayList("gaoxueyafenxi");
        return R.ok().put("token", token).put("tableName", strings);
    }

    /**
     * 注册
     */
    @IgnoreAuth
    @RequestMapping("/register")
    public R register(@RequestBody YiShengEntity yisheng) {
        //ValidatorUtils.validateEntity(yisheng);
        YiShengEntity user = yonghuService.selectOne(new EntityWrapper<YiShengEntity>().eq("yonghuzhanghao", yisheng.getYonghuzhanghao()));
        if (user != null) {
            return R.error("注册用户已存在");
        }
        Long uId = new Date().getTime();
        yisheng.setId(uId);
        yonghuService.insert(yisheng);
        return R.ok();
    }


    /**
     * 退出
     */
    @RequestMapping("/logout")
    public R logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return R.ok("退出成功");
    }

    /**
     * 获取用户的session用户信息
     */
    @RequestMapping("/session")
    public R getCurrUser(HttpServletRequest request) {
        Long id = (Long) request.getSession().getAttribute("userId");
        YiShengEntity user = yonghuService.selectById(id);
        return R.ok().put("data", user);
    }

    /**
     * 密码重置
     */
    @IgnoreAuth
    @RequestMapping(value = "/resetPass")
    public R resetPass(String username, HttpServletRequest request) {
        YiShengEntity user = yonghuService.selectOne(new EntityWrapper<YiShengEntity>().eq("yonghuzhanghao", username));
        if (user == null) {
            return R.error("账号不存在");
        }
        user.setMima("123456");
        yonghuService.updateById(user);
        return R.ok("密码已重置为：123456");
    }


    /**
     * 后端列表
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params, YiShengEntity yisheng,
                  HttpServletRequest request) {

        String tableName = request.getSession().getAttribute("tableName").toString();
        if (tableName.equals("yisheng")) {
            yisheng.setYonghuzhanghao((String) request.getSession().getAttribute("username"));
        }
        EntityWrapper<YiShengEntity> ew = new EntityWrapper<YiShengEntity>();
        PageUtils page = yonghuService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, yisheng), params), params));

        return R.ok().put("data", page);
    }

    /**
     * 前端列表
     */
    @IgnoreAuth
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params, YiShengEntity yisheng,
                  HttpServletRequest request) {
        EntityWrapper<YiShengEntity> ew = new EntityWrapper<YiShengEntity>();
        PageUtils page = yonghuService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, yisheng), params), params));
        return R.ok().put("data", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/lists")
    public R list(YiShengEntity yisheng) {
        EntityWrapper<YiShengEntity> ew = new EntityWrapper<YiShengEntity>();
        ew.allEq(MPUtil.allEQMapPre(yisheng, "yisheng"));
        return R.ok().put("data", yonghuService.selectListView(ew));
    }

    /**
     * 查询
     */
    @RequestMapping("/query")
    public R query(YiShengEntity yisheng) {
        EntityWrapper<YiShengEntity> ew = new EntityWrapper<YiShengEntity>();
        ew.allEq(MPUtil.allEQMapPre(yisheng, "yisheng"));
        YonghuView yonghuView = yonghuService.selectView(ew);
        return R.ok("查询用户成功").put("data", yonghuView);
    }

    /**
     * 后端详情
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        YiShengEntity yisheng = yonghuService.selectById(id);
        return R.ok().put("data", yisheng);
    }

    /**
     * 前端详情
     */
    @IgnoreAuth
    @RequestMapping("/detail/{id}")
    public R detail(@PathVariable("id") Long id) {
        YiShengEntity yisheng = yonghuService.selectById(id);
        return R.ok().put("data", yisheng);
    }

    /**
     * 后端保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody YiShengEntity yisheng, HttpServletRequest request) {
        yisheng.setId(new Date().getTime() + new Double(Math.floor(Math.random() * 1000)).longValue());
        //ValidatorUtils.validateEntity(yisheng);

        YiShengEntity user = yonghuService.selectOne(new EntityWrapper<YiShengEntity>().eq("yonghuzhanghao", yisheng.getYonghuzhanghao()));
        if (user != null) {
            return R.error("用户已存在");
        }

        yisheng.setId(new Date().getTime());

        yonghuService.insert(yisheng);
        return R.ok();
    }

    /**
     * 前端保存
     */
    @RequestMapping("/add")
    public R add(@RequestBody YiShengEntity yisheng, HttpServletRequest request) {
        yisheng.setId(new Date().getTime() + new Double(Math.floor(Math.random() * 1000)).longValue());
        //ValidatorUtils.validateEntity(yisheng);

        YiShengEntity user = yonghuService.selectOne(new EntityWrapper<YiShengEntity>().eq("yonghuzhanghao", yisheng.getYonghuzhanghao()));
        if (user != null) {
            return R.error("用户已存在");
        }

        yisheng.setId(new Date().getTime());
        yonghuService.insert(yisheng);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@Transactional
    public R update(@RequestBody YiShengEntity yisheng, HttpServletRequest request) {
        //ValidatorUtils.validateEntity(yisheng);
        yisheng.setTouxiang(extractUploadPath(yisheng.getTouxiang()));
        yonghuService.updateById(yisheng);//全部更新
        return R.ok();
    }

    public static String extractUploadPath(String url) {
        // 定义目标路径的起始部分
        String startMarker = "/upload/";

        // 查找 "/upload/" 的起始索引
        int startIndex = url.indexOf(startMarker);

        // 如果找到了 "/upload/"
        if (startIndex != -1) {
            // 截取从 "/upload/" 开始的部分
            return url.substring(startIndex);
        }

        // 如果未找到，返回空字符串或其他提示信息
        return "";
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        yonghuService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     * 提醒接口
     */
    @RequestMapping("/remind/{columnName}/{type}")
    public R remindCount(@PathVariable("columnName") String columnName, HttpServletRequest request,
                         @PathVariable("type") String type, @RequestParam Map<String, Object> map) {
        map.put("column", columnName);
        map.put("type", type);

        if (type.equals("2")) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            Date remindStartDate = null;
            Date remindEndDate = null;
            if (map.get("remindstart") != null) {
                Integer remindStart = Integer.parseInt(map.get("remindstart").toString());
                c.setTime(new Date());
                c.add(Calendar.DAY_OF_MONTH, remindStart);
                remindStartDate = c.getTime();
                map.put("remindstart", sdf.format(remindStartDate));
            }
            if (map.get("remindend") != null) {
                Integer remindEnd = Integer.parseInt(map.get("remindend").toString());
                c.setTime(new Date());
                c.add(Calendar.DAY_OF_MONTH, remindEnd);
                remindEndDate = c.getTime();
                map.put("remindend", sdf.format(remindEndDate));
            }
        }

        Wrapper<YiShengEntity> wrapper = new EntityWrapper<YiShengEntity>();
        if (map.get("remindstart") != null) {
            wrapper.ge(columnName, map.get("remindstart"));
        }
        if (map.get("remindend") != null) {
            wrapper.le(columnName, map.get("remindend"));
        }

        String tableName = request.getSession().getAttribute("tableName").toString();
        if (tableName.equals("yisheng")) {
            wrapper.eq("yonghuzhanghao", (String) request.getSession().getAttribute("username"));
        }
        int count = yonghuService.selectCount(wrapper);
        return R.ok().put("count", count);
    }

    /**
     * （按值统计）
     */
    @RequestMapping("/value/{xColumnName}/{yColumnName}")
    public R value(@PathVariable("yColumnName") String yColumnName, @PathVariable("xColumnName") String xColumnName, HttpServletRequest request) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("xColumn", xColumnName);
        params.put("yColumn", yColumnName);
        EntityWrapper<YiShengEntity> ew = new EntityWrapper<YiShengEntity>();
        String tableName = request.getSession().getAttribute("tableName").toString();
		/*if(tableName.equals("yisheng")) {
            ew.eq("yonghuming", (String)request.getSession().getAttribute("username"));
		}*/
        List<Map<String, Object>> result = yonghuService.selectValue(params, ew);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (Map<String, Object> m : result) {
            for (String k : m.keySet()) {
                if (m.get(k) instanceof Date) {
                    m.put(k, sdf.format((Date) m.get(k)));
                }
            }
        }
        return R.ok().put("data", result);
    }

    /**
     * （按值统计）时间统计类型
     */
    @RequestMapping("/value/{xColumnName}/{yColumnName}/{timeStatType}")
    public R valueDay(@PathVariable("yColumnName") String yColumnName, @PathVariable("xColumnName") String xColumnName, @PathVariable("timeStatType") String timeStatType, HttpServletRequest request) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("xColumn", xColumnName);
        params.put("yColumn", yColumnName);
        params.put("timeStatType", timeStatType);
        EntityWrapper<YiShengEntity> ew = new EntityWrapper<YiShengEntity>();
        String tableName = request.getSession().getAttribute("tableName").toString();
       /* if(tableName.equals("yisheng")) {
            ew.eq("yonghuming", (String)request.getSession().getAttribute("username"));
        }*/
        List<Map<String, Object>> result = yonghuService.selectTimeStatValue(params, ew);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (Map<String, Object> m : result) {
            for (String k : m.keySet()) {
                if (m.get(k) instanceof Date) {
                    m.put(k, sdf.format((Date) m.get(k)));
                }
            }
        }
        return R.ok().put("data", result);
    }

    /**
     * 分组统计
     */
    @RequestMapping("/group/{columnName}")
    public R group(@PathVariable("columnName") String columnName, HttpServletRequest request) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("column", columnName);
        EntityWrapper<YiShengEntity> ew = new EntityWrapper<YiShengEntity>();
        String tableName = request.getSession().getAttribute("tableName").toString();
        /*if(tableName.equals("yisheng")) {
            ew.eq("yonghuming", (String)request.getSession().getAttribute("username"));
        }*/
        List<Map<String, Object>> result = yonghuService.selectGroup(params, ew);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (Map<String, Object> m : result) {
            for (String k : m.keySet()) {
                if (m.get(k) instanceof Date) {
                    m.put(k, sdf.format((Date) m.get(k)));
                }
            }
        }
        return R.ok().put("data", result);
    }

    /**
     * 总数量
     */
    @RequestMapping("/count")
    public R count(@RequestParam Map<String, Object> params, YiShengEntity yisheng, HttpServletRequest request) {
        String tableName = request.getSession().getAttribute("tableName").toString();

        EntityWrapper<YiShengEntity> ew = new EntityWrapper<YiShengEntity>();
        int count = yonghuService.selectCount(MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, yisheng), params), params));
        return R.ok().put("data", count);

    }

//    @Autowired
//    private MessageService messageService;

//    @PostMapping("send")
//    public R send(@RequestBody MessageEntity message, HttpServletRequest request) {
//        Integer isAdmin = message.getIsAdmin();
//        if (isAdmin == 0) {
//            Object userId = request.getSession().getAttribute("userId");
//            YiShengEntity yonghuEntity = yonghuService.selectById(userId.toString());
//            message.setUsername(yonghuEntity.getYonghuxingming());
//            message.setUserId(Integer.parseInt(userId.toString()));
//        }
//        if (isAdmin == 1) {
//            Object userId = request.getSession().getAttribute("userId");
//            UsersEntity admin = usersService.selectById(userId.toString());
//            message.setUsername(admin.getUsername());
//            message.setUserId(Integer.parseInt(admin.getId().toString()));
//        }
//
//        if (StrUtil.isNotBlank(message.getReceiveUser()) && Objects.isNull(message.getToUserId())) {
//            YiShengEntity receiveUser = yonghuService.selectByName(message.getReceiveUser());
//            receiveUser.getId();
//            message.setToUserId(receiveUser.getId().intValue());
//        }
//
//
//        message.setAddTime(LocalDateTime.now());
//        messageService.insert(message);
//        return R.ok();
//    }

//    @PostMapping("list")
//    public R list(HttpServletRequest request) {
//        Wrapper wrapper = new EntityWrapper();
//        Object userId = request.getSession().getAttribute("userId");
//        wrapper.eq("user_id", userId).or().eq("to_user_id", userId).orderBy("add_time", false);
//        List<MessageEntity> list = messageService.selectList(wrapper);
//        return R.ok().put("data", list);
//    }


//    @PostMapping("listForAdmin")
//    public R listForAdmin() {
//        Wrapper wrapper = new EntityWrapper();
//        wrapper.orderBy("add_time", false);
//        List<MessageEntity> list = messageService.selectList(wrapper);
//        return R.ok().put("data", list);
//    }

}